﻿using IOA.MES.Client.Common;
using IOA.MES.Client.Models.Response;
using IOA.MES.Common;
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;

namespace IOA.MES.Client.EL2
{
    /// <summary>
    /// WinPassEL2.xaml 的交互逻辑
    /// </summary>
    public partial class WinPassEL2 : Window
    {
        private List<KeyValuePair<string, string>> ivDatas = new List<KeyValuePair<string, string>>();
        private string lastImage = string.Empty;
        private string curDirectory;
        public WinPassEL2()
        {
            InitializeComponent();
        }

        private void TryViaSite(string barCode)
        {
            try
            {
                var images = Directory.GetFiles(txtImageFolder.Text, "*", SearchOption.AllDirectories).Where(_ => _.EndsWith(".jpg", StringComparison.CurrentCultureIgnoreCase)).ToList();
                var imagePaths = images.Where(_ => _.ToUpper().Contains(barCode)).ToList();
                var imagePath = imagePaths.Any(_ => _.ToUpper().Contains("OK")) ? imagePaths.FirstOrDefault(_ => _.ToUpper().Contains("OK")) : imagePaths.FirstOrDefault();

                if (string.IsNullOrWhiteSpace(imagePath))
                {
                    CommonMessage.Log(LogLevel.Warn, $"条码图片不存在：{barCode}");
                    return;
                }
                var viaSiteRequest = new
                {
                    SiteType = SiteType.EL2,
                    DutyId = 1,
                    MachineId = BaseEnv.MachineId,
                    Code = barCode,
                    QLevel = imagePath.ToUpper().Contains("OK") ? "Q1" : "QB",
                    Images = new List<string> { }
                };
                try
                {
                    var getComponentResponse = BaseEnv.InvokeApi<GetComponentResponse>("/api/Machine/GetComponent", new { BarCode = barCode });
                    if (getComponentResponse.ErrCode != 200)
                    {
                        mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                        mediaElResult.Play();
                        CommonMessage.Log(LogLevel.Warn, getComponentResponse.ErrMsg);
                        //CommonMessage.Alert(this, getComponentResponse.ErrMsg, false);
                        return;
                    }
                    else if (getComponentResponse.Data == null || getComponentResponse.Data.Component == null)
                    {
                        mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                        mediaElResult.Play();
                        CommonMessage.Log(LogLevel.Warn, $"组件不存在:{barCode}");
                        //CommonMessage.Alert(this, $"Thành phần không tồn tại\r\n组件不存在\r\nComponent does not exist：\r\n{barCode}", false);
                        return;
                    }
                    var tmpDirectory = $"/{BaseEnv.WorkshopCode}/el2/{getComponentResponse.Data.Component.WorkOrderNo}";
                    if (string.IsNullOrWhiteSpace(curDirectory) || !string.Equals(curDirectory, tmpDirectory, StringComparison.CurrentCultureIgnoreCase))
                    {
                        new FtpUtils(BaseEnv.UserInfo.FtpConfig.FtpRoot, BaseEnv.UserInfo.FtpConfig.UserName, BaseEnv.UserInfo.FtpConfig.Password).CheckAndCreateDirectory(tmpDirectory);
                        curDirectory = tmpDirectory;
                    }
                    var fileName = $"{curDirectory}/{System.IO.Path.GetFileName(imagePath)}";
                    new FtpUtils(BaseEnv.UserInfo.FtpConfig.FtpRoot, BaseEnv.UserInfo.FtpConfig.UserName, BaseEnv.UserInfo.FtpConfig.Password).Upload(File.ReadAllBytes(imagePath), fileName);
                    viaSiteRequest.Images.Add($"{BaseEnv.UserInfo.FtpConfig.FtpRoot}{fileName}");
                }
                catch (Exception ex)
                {
                    CommonMessage.Log(LogLevel.Warn, $"图片上传失败:{barCode},{ex.Message}", ex);
                    //CommonMessage.Alert(this, $"Tải ảnh không thành công, vui lòng chụp ảnh mới\r\n图片上传失败，请重新拍照\r\nPicture upload failed, please take a new picture\r\n{ex.Message}", false);
                    return;
                }

                var response = BaseEnv.InvokeApi<ViaSiteResponse>("/api/Machine/ViaSite", viaSiteRequest);
                if (response.ErrCode != 200)
                {
                    mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                    mediaElResult.Play();
                    CommonMessage.Log(LogLevel.Warn, $"过站失败:{barCode},{response.ErrMsg}");
                    //CommonMessage.Alert(this, response.ErrMsg, false);
                    return;
                }

                mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Success.wav");
                mediaElResult.Play();
            }
            catch (Exception ex)
            {
                CommonMessage.Log(LogLevel.Warn, $"过站失败:{barCode},{ex.Message}", ex);
                //CommonMessage.Alert(this, $"Phần mềm không bình thường, vui lòng chụp ảnh và gửi cho IT\r\n过站失败，请拍照发给IT，并重新尝试过站\r\nPassing failed, please take a picture and send it to IT\r\n{ex.ToString()}", false);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var barCodes = txtBarCode.Text.Trim().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            if (!barCodes.Any())
            {
                MessageBox.Show("条码为空");
                return;
            }

            foreach (var barCode in barCodes)
            {
                try
                {
                    TryViaSite(barCode);
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show($"条码过站异常，条码：{barCode}，异常信息：{ex.ToString()}");
                }
            }
            MessageBox.Show("处理完成");
        }
    }
}
